package pxene.test

import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.HColumnDescriptor
import org.apache.hadoop.hbase.HTableDescriptor
import org.apache.hadoop.hbase.TableName
import org.apache.hadoop.hbase.client.ConnectionFactory
import org.apache.hadoop.hbase.client.Delete
import org.apache.hadoop.hbase.client.Get
import org.apache.hadoop.hbase.client.Put
import org.apache.hadoop.hbase.client.Scan
import org.apache.hadoop.hbase.filter.PageFilter
import org.apache.hadoop.hbase.util.Bytes

object HBaseNewAPI {
  val conf = HBaseConfiguration.create()
  conf.set("hbase.zookeeper.property.clientPort", "2181")
  conf.set("hbase.zookeeper.quorum", "dmp01,dmp02,dmp03,dmp04,dmp05")

  //Connection 的创建是个重量级的工作，线程安全，是操作hbase的入口
  val conn = ConnectionFactory.createConnection(conf)
  def main(args: Array[String]): Unit = {

    val userTable = TableName.valueOf("t_article_classify")

    //从Connection获得 Admin 对象(相当于以前的 HAdmin)
    val admin = conn.getAdmin
    //创建 user 表
    val tableDescr = new HTableDescriptor(userTable)
    tableDescr.addFamily(new HColumnDescriptor("article".getBytes))
    println("Creating table `user`. ")
    if (admin.tableExists(userTable)) {
      admin.disableTable(userTable)
      admin.deleteTable(userTable)
    }
    admin.createTable(tableDescr)
    println("Done!")

    //获取 user 表
    val table = conn.getTable(userTable)
    try {

      //根据过滤器扫描数据
      val filter = new PageFilter(10);
      val s = new Scan()
      s.setFilter(filter);
      s.addColumn("article".getBytes, "content".getBytes)
      val scanner = table.getScanner(s)
      try {
        val it = scanner.iterator()
        while (it.hasNext()) {
          val r = it.next()
          println("Found row: " + Bytes.toString(r.getRow))
          println("Found value: " + Bytes.toString(r.getValue("article".getBytes, "content".getBytes)))
        }
      } finally {
        //确保scanner关闭
        scanner.close()
      }

      //插入数据
      //准备插入一条 key 为 id001 的数据
      val p = new Put("id001".getBytes)
      //为put操作指定 column 和 value （以前的 put.add 方法被弃用了）
      p.addColumn("article".getBytes, "title".getBytes, "abcddfdf".getBytes)
      //提交
      table.put(p)

      //查询某条数据
      val g = new Get("id001".getBytes)
      val result = table.get(g)
      val value = Bytes.toString(result.getValue("basic".getBytes, "name".getBytes))
      println("GET id001 :" + value)

      //删除某条数据,操作方式与 Put 类似
      val d = new Delete("id001".getBytes)
      d.addColumn("basic".getBytes, "name".getBytes)
      table.delete(d)

    } finally {
      if (table != null) table.close()
      conn.close()
    }
  }
}